package com.atguigu.tingshu.search.service.impl;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 获取专辑详情信息
     * 1. 通过专辑Id 获取专辑数据{已存在}
     * 2. 通过专辑Id 获取专辑统计信息{不存在}
     * 3. 通过三级分类Id 获取到分类数据{已存在}
     * 4. 通过用户Id 获取到作者信息{已存在}
     * @param albumId
     * @return
     */
    @Override
    public Map<String, Object> getItem(Long albumId) {

        //  创建map集合;
        Map<String, Object> result = new HashMap<>();
        //远程调用接口之前 提前知道用户访问的专辑id是否存在与布隆过滤器
        /*RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        if (!bloomFilter.contains(albumId)) {
            log.error("用户查询专辑不存在：{}", albumId);
            //查询数据不存在直接返回空对象
            return result;
        }*/
        //远程调用获取专辑详细信息
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //远程调用
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            //判断
            Assert.notNull(albumInfoResult, "获取专辑信息失败");
            //获取专辑信息
            AlbumInfo albumInfo = albumInfoResult.getData();
            //判断
            Assert.notNull(albumInfo, "获取专辑信息失败");
            // 存储数据
            result.put("albumInfo", albumInfo);
            //返回专辑信息
            return albumInfo;
        }, threadPoolExecutor).whenCompleteAsync((v, t) -> {
            System.out.println("专辑标题：\t" + v.getAlbumTitle());
            if (t != null) {
                log.error("查询分类数据失败：{}", t.getMessage());
            }
        });

        //因为下边获取分类信息要用到albumInfo中的category3Id,所以此处要先获取albumInfo
        CompletableFuture<Void> cateCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //远程调用
            Result<BaseCategoryView> baseCategoryViewResult = categoryFeignClient.getBaseCategoryView(albumInfo.getCategory3Id());
            //判断
            Assert.notNull(baseCategoryViewResult, "分类信息获取失败");
            //获取分类信息
            BaseCategoryView baseCategoryView = baseCategoryViewResult.getData();
            //判断
            Assert.notNull(baseCategoryView, "分类信息获取失败");
            //  存储数据
            result.put("baseCategoryView", baseCategoryView);

        }, threadPoolExecutor).whenCompleteAsync((v, t) -> {
            if (t != null) {
                log.error("查询分类数据失败：{}", t.getMessage());
            }
        });

        //  获取用户Id，获取用户信息
        CompletableFuture<Void> userCompleteFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //远程调用
            Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(albumInfo.getUserId());
            //判断
            Assert.notNull(userInfoVoResult, "获取用户信息失败");
            //获取用户信息
            UserInfoVo userInfoVo = userInfoVoResult.getData();
            //判断
            Assert.notNull(userInfoVo, "获取用户信息失败");
            //  存储数据
            result.put("announcer", userInfoVo);
        }, threadPoolExecutor).whenCompleteAsync((v, t) -> {
            if (t != null) {
                log.error("查询作者数据失败：{}", t.getMessage());
            }
        });

        //根据专辑Id 查询专辑统计数据;
        CompletableFuture<Void> statCompletableFuture = CompletableFuture.runAsync(() -> {
            //远程调用
            Result<AlbumStatVo> albumStatVoResult = albumInfoFeignClient.getAlbumStatVo(albumId);
            //判断
            Assert.notNull(albumStatVoResult, "查询专辑统计数据失败");
            //获取统计信息
            AlbumStatVo albumStatVo = albumStatVoResult.getData();
            //判断
            Assert.notNull(albumStatVo, "查询专辑统计数据失败");
            //  存储数据
            result.put("albumStatVo", albumStatVo);
        }, threadPoolExecutor).whenCompleteAsync((v, t) -> {
            if (t != null) {
                log.error("查询统计数据失败：{}", t.getMessage());
            }
        });

        //  多任务组合：
        try {
            CompletableFuture.allOf(albumInfoCompletableFuture, cateCompletableFuture, userCompleteFuture, statCompletableFuture).join();
        } catch (Exception e) {
            throw new GuiguException(8888, "查询专辑数据失败");
        }
        //返回数据
        return result;
    }
}
